import {Component, OnInit} from '@angular/core';
import {NavController} from '@ionic/angular';
import {QRScanner, QRScannerStatus} from '@ionic-native/qr-scanner/ngx';
import {EventService} from '../common/service/event.service';

@Component({
    selector: 'app-qrscan',
    templateUrl: './qrscan.page.html',
    styleUrls: ['./qrscan.page.less'],
})

export class QrscanPage implements OnInit {

    public light: boolean; // 判断闪光灯
    public frontCamera: boolean; // 判断摄像头
    public isShow: boolean = false; // 控制显示背景，避免切换页面卡顿

    /****************************************************************/
    public receivedData; // 接收到的数据（来自url）
    public scanText = null; // 扫码识别到的数据


    constructor(
        private qrScanner: QRScanner,
        public navController: NavController,
        public eventService: EventService,
    ) {
        // 下面格式化必须要有
        const sendDataToScanPage = localStorage.getItem('sendDataToScanPage');
        if (sendDataToScanPage) {
            this.receivedData = JSON.parse(JSON.stringify(sendDataToScanPage));
        } else {
            this.receivedData = null;
        }
    }

    ngOnInit() {
        // this.ionViewWillEnter() ;
    }

    // 刚进来的时候执行扫码
    ionViewWillEnter() {

        this.qrScanner.prepare()
            .then((status: QRScannerStatus) => {
                if (status.authorized) {
                    // start scanning
                    let scanSub = this.qrScanner.scan().subscribe((text: string) => {
                        // console.log('Scanned something', text);
                        // alert(text);
                        this.scanText = text;
                        this.qrScanner.hide(); // hide camera preview
                        scanSub.unsubscribe(); // stop scanning
                        this.navController.back();
                    });
                    // 打开摄像头
                    this.qrScanner.show();
                } else if (status.denied) {
                    // console.log('没有摄像头权限，请前往设置中开启');
                    alert('没有摄像头权限，请前往设置中开启');
                } else {
                    // permission was denied, but not permanently. You can ask for permission
                    // console.log('没有摄像头权限，请前往设置中开启');
                    alert('没有摄像头权限，请前往设置中开启');
                }
            })
            .catch((e: any) => {
                // console.log('Error is', e);
                alert('Error is ' + JSON.stringify(e));
            });
    }

    ionViewDidLeave() {
        // 扫码页面返回的时候发送广播
        this.eventService.eventEmit.emit('scanPageCloseEvent', this.scanText);
    }


    /*页面可见后执行 */
    ionViewDidEnter() {
        this.isShow = true; // 显示背景
        // console.log('ionViewDidEnter');
    }


    /**
     * 闪光灯控制，默认关闭
     */
    toggleLight() {
        if (this.light) {
            this.qrScanner.disableLight();
        } else {
            this.qrScanner.enableLight();
        }
        this.light = !this.light;
    }

    /**
     * 前后摄像头互换
     */
    toggleCamera() {
        if (this.frontCamera) {
            this.qrScanner.useBackCamera();
        } else {
            this.qrScanner.useFrontCamera();
        }
        this.frontCamera = !this.frontCamera;
    }

    //组件销毁
    ionViewWillLeave() {
        this.qrScanner.hide(); // 需要关闭扫描，否则相机一直开着
        this.qrScanner.destroy(); // 关闭
    }

}
